import express from 'express';
import { formatError, formatSuccess } from '../utils/helpers.js';

export function createRoomsRouter(roomManager) {
  const router = express.Router();

  // 获取房间列表
  router.get('/', async (req, res) => {
    try {
      const limit = parseInt(req.query.limit) || 20;
      console.log(`收到房间列表请求，限制: ${limit}`);
      const rooms = await roomManager.getAvailableRooms(limit);
      console.log(`返回房间数据:`, rooms);
      res.json(formatSuccess(rooms, '获取房间列表成功'));
    } catch (error) {
      console.error('房间列表API错误:', error);
      res.status(500).json(formatError('SERVER_ERROR', `服务器内部错误: ${error.message}`));
    }
  });

  // 获取房间详情
  router.get('/:roomId', async (req, res) => {
    try {
      const { roomId } = req.params;
      const room = await roomManager.getRoomById(roomId);
      
      if (!room) {
        return res.status(404).json(formatError('ROOM_NOT_FOUND', '房间不存在'));
      }

      res.json(formatSuccess(room, '获取房间详情成功'));
    } catch (error) {
      res.status(500).json(formatError('SERVER_ERROR', '服务器内部错误'));
    }
  });

  // 创建房间（HTTP方式，主要用于测试）
  router.post('/', async (req, res) => {
    try {
      const { roomName, playerName } = req.body;
      
      if (!roomName || !playerName) {
        return res.status(400).json(formatError('INVALID_INPUT', '房间名和玩家名不能为空'));
      }

      const result = await roomManager.createRoom(roomName, playerName);
      
      if (result.success) {
        res.status(201).json(formatSuccess(result.data, '房间创建成功'));
      } else {
        res.status(400).json(formatError('CREATE_FAILED', result.message));
      }
    } catch (error) {
      res.status(500).json(formatError('SERVER_ERROR', '服务器内部错误'));
    }
  });

  return router;
}